//
//  LocalTestViewController.m
//  LocalTest
//
//  Created by Pibinuo on 15/12/4.
//  Copyright © 2015年 皮比诺. All rights reserved.
//

#import "LocalTestViewController.h"
#import "LocalController.h"
#import <CoreLocation/CoreLocation.h>
#import "Modefy.h"
#import "NewsOneTableViewCell.h"
#import "NewsTwoTableViewCell.h"
#import "Topic2TableViewCell.h"
#import "NoImageTableViewCell.h"
#import "LocalHelper.h"
#import "LocalLIst.h"
#import "LocalDetailViewController.h"
#import "UIImageView+WebCache.h"

@interface LocalTestViewController ()<CLLocationManagerDelegate,localControllerDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView * tableView;

@property (nonatomic, assign) NSInteger count;

@property (nonatomic, assign) CGFloat height;

//定位
@property (nonatomic, strong) CLLocationManager * manager;

@property (nonatomic, strong) CLGeocoder * georoder;

@property (nonatomic, strong) NSString * province;//省
@property (nonatomic, strong) NSString * city;//市
@property (nonatomic, strong) NSString * district;//区

@property (nonatomic, strong) NSString * choicetype;
@property (nonatomic, strong) NSString * choicename;


@end

@implementation LocalTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位未打开，请设置打开");
        return;
    }
    [self.manager requestAlwaysAuthorization];
    self.manager.delegate = self;
    [self.manager startUpdatingLocation];
    self.manager.desiredAccuracy = kCLLocationAccuracyBest;
    if (self.city == nil) {
        self.navigationItem.title = [NSString stringWithFormat:@"正在定位"];
    } else {
        self.navigationItem.title = [NSString stringWithFormat:@"当前的城市是：%@",self.city];
    }
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //注册
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[NewsOneTableViewCell class] forCellReuseIdentifier:@"cell_one"];
    [self.tableView registerClass:[NewsTwoTableViewCell class] forCellReuseIdentifier:@"cell_two"];
    [self.tableView registerClass:[Topic2TableViewCell class] forCellReuseIdentifier:@"cell_topic2"];
    [self.tableView registerClass:[NoImageTableViewCell class] forCellReuseIdentifier:@"cell_noimage"];
    
    self.count = 1;
    //通知刷新UI
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishData) name:@"finishNews" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(finishLocal) name:@"finishLocal" object:nil];
    
//    [self.navigationController.navigationBar setTintColor:[UIColor redColor]];
    //右侧重新定位
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"dingwei"] style:(UIBarButtonItemStyleDone) target:self action:@selector(rightBarButtonItemAction:)];
    
    
}

//重新选择位置
-(void)rightBarButtonItemAction:(UIBarButtonItem *)sender
{
    LocalController * localVC = [[LocalController alloc]initWithStyle:(UITableViewStyleGrouped)];
    localVC.localCity = self.city;
    localVC.nowCity = self.navigationItem.title;
    localVC.delegate = self;
    UINavigationController * localNC = [[UINavigationController alloc]initWithRootViewController:localVC];
    [self presentViewController:localNC animated:YES completion:nil];
}

-(void)finishData
{
    if (self.choicename == nil) {
        self.navigationItem.title = self.city;
    } else {
        self.navigationItem.title = self.choicename;
    }
    [self.tableView reloadData];
}
-(void)finishLocal
{
    [[LocalHelpers defaultHelpers] removeAll];
    if (self.city != nil || self.province != nil) {
        NSMutableString * str1 = [self.classify.api mutableCopy];
        NSString * str2 = [NSString stringWithFormat:@"?province=%@&city=%@&district=%@", self.province, self.city, self.district];
        [str1 appendString:str2];
        
        [LocalHelpers defaultHelpers].urlStr = str1;
        [[LocalHelpers defaultHelpers] reloadData];
    }
    [self.manager stopUpdatingLocation];
}

#pragma mark --- 城市选择的代理方法
-(void)passValue:(LocalLIst *)local
{
    self.choicetype = local.type;
    self.choicename = local.name;
    [[LocalHelpers defaultHelpers] removeAll];
//    NSMutableString * str1 = [self.classify.api mutableCopy];
    NSMutableString * str1 = @"http://api.irecommend.ifeng.com/local.php".mutableCopy;
    NSString * str2 = [NSString stringWithFormat:@"?&choicetype=%@&choicename=%@", self.choicetype, self.choicename];
    [str1 appendString:str2];
    
    [LocalHelpers defaultHelpers].urlStr = str1;
//    [LocalHelpers defaultHelpers].urlStr = @"http://api.irecommend.ifeng.com/local.php?&choicetype=city&choicename=包头";
    [[LocalHelpers defaultHelpers] reloadData];
}

-(void)loadData
{
    [LocalHelpers defaultHelpers].urlStr = @"http://api.irecommend.ifeng.com/local.php?&choicetype=city&choicename=北京";
    [[LocalHelpers defaultHelpers] reloadData];

}


#pragma mark --- 定位代理的方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation * location = locations.firstObject;
    [self.georoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark * placeMark = placemarks.firstObject;
        self.province = placeMark.administrativeArea;
        self.city = placeMark.locality;
        self.district = placeMark.subLocality;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"finishLocal" object:nil];
        });
        
    }];
}



#pragma TableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //NSLog(@"%ld", [[LocalHelpers defaultHelpers] modelCount]);
    return [[LocalHelpers defaultHelpers] modelCount];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    News * news = [[LocalHelpers defaultHelpers] modelWithIndex:indexPath.row];
    
    //NewsOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_one" forIndexPath:indexPath];
    
    if ([news.type isEqualToString:@"doc"]) {
        if (news.thumbnail.length == 0) {
            NoImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_noimage" forIndexPath:indexPath];
            cell.timeLable.text = news.updateTime;
            cell.titleLable.text = news.title;
            cell.commentLable.text = news.commentsall;
            return cell;
        }else{
            
            NewsOneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_one" forIndexPath:indexPath];
            cell.timeLable.text = news.updateTime;
            cell.titleLable.text = news.title;
            cell.commentLable.text = news.commentsall;
            [cell.image sd_setImageWithURL:[NSURL URLWithString:news.thumbnail]];
            return cell;
        }
    }else if ([news.type isEqualToString:@"slide"]){
        NewsTwoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_two" forIndexPath:indexPath];
        cell.timeLable.text = news.updateTime;
        cell.titleLable.text = news.title;
        cell.commentLable.text = news.commentsall;
        NSArray * array = news.style[@"images"];
        //NSLog(@"%@", array);
        [cell.image1 sd_setImageWithURL:[NSURL URLWithString:array[0]]];
        [cell.image2 sd_setImageWithURL:[NSURL URLWithString:array[1]]];
        [cell.image3 sd_setImageWithURL:[NSURL URLWithString:array[2]]];
        return cell;
    }else if ([news.type isEqualToString:@"topic2"]){
        Topic2TableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell_topic2" forIndexPath:indexPath];
        cell.titleLable.text = news.title;
        cell.commentLable.text = news.commentsall;
        [cell.image sd_setImageWithURL:[NSURL URLWithString:news.thumbnail]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    News * news = [[LocalHelpers defaultHelpers] modelWithIndex:indexPath.row];
    if ([news.type isEqualToString:@"doc"] || [news.type isEqualToString:@"topic2"]) {
        
        if (news.thumbnail.length == 0) {
            return 65;
        }else{
            return 80;
        }
    }else if([news.type isEqualToString:@"slide"]){
        return 120;
    }else {
        return 80;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LocalDetailViewController * detailVC = [[LocalDetailViewController alloc] init];
    detailVC.index = indexPath.row;
    [self.navigationController pushViewController:detailVC animated:YES];
}



//懒加载
- (CLLocationManager *)manager
{
    if (_manager == nil) {
        self.manager = [[CLLocationManager alloc] init];
    }
    return _manager;
}

- (CLGeocoder *)georoder
{
    if (_georoder == nil) {
        self.georoder = [[CLGeocoder alloc] init];
    }
    return _georoder;
}

-(Modefy *)classify
{
    if (_classify == nil) {
        self.classify = [[Modefy alloc]init];
    }
    return _classify;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
